import axios from "axios";
import { Loading ,Message } from 'element-ui';
import router from "@/router"
let baseURL = "http://localhost:3000/"
axios.defaults.baseURL =   baseURL  // 请求的基路径  
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let load = null;
export function  showLoading(){
    load && load.close() ; 
    load = Loading.service({
        lock: true,
        text: '请求中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    });
}

export function showSuccess(msg){
    msg = msg || "请求成功";
    load && load.close() ; 
    Message.success({
        message: msg,
        center: true,
        duration:1200,
        showClose: true,
    })
}

export function showError(msg){
    msg = msg || "请求失败"
    load && load.close() ; 
    Message.error({
        message: msg,
        center: true,
        showClose: true,
        duration:1200
    })
}

// Interceptors 拦截器 
//  请求发送之前的拦截器 
axios.interceptors.request.use(function (config) {
// 请求发送之前做的事情 
    
    var token = sessionStorage.getItem("token");
    if(token){
        config.headers['token'] = token;
    }
    showLoading()
    return config;
}, function (error) {
// 请求发送失败 
    showError('请求发送失败');
    return Promise.reject(error);
});




// 响应结束之前的拦截器 
axios.interceptors.response.use(function (response) {
    // 状态码判断 
    // 打印 返回的数据 
    // console.log(response.data)  // axios 的数据存在data 
    setTimeout(()=>{
        if(response.data.type){
            showSuccess(response.data.msg);
        }else{
            if(response.data.type==0){
                showError(response.data.msg);
            }else{
                showSuccess(response.data.msg);
            }
        }
    },500)

    if(response.data.code=="3200"){
        // token 有问题  重新登录
        router.push({name:"login"})
    }

    return response;
  }, function (error) {
    // 响应失败 
    showError('响应失败')
    return Promise.reject(error);
});

export const get =(url,params)=>{
    return new Promise(function(resolve,reject){
        axios.get(url,{
            params
        })
        .then(res=>{
            resolve(res.data)
        })
        .catch(err=>{
            reject(err)
        })
    })
}
//封装promise
export const post = (url,params)=>{
    return new Promise(function(resolve,reject){
        axios.post(url,params)
        .then(res=>{
            resolve(res.data)   // res.data  
        })
        .catch(err=>{
            reject(err);
        })
    })
}

export { axios,baseURL }; 

